<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use QL\QueryList;
use App\Models\Movie;

class GetMovieShortName extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'daka:get-movie-short-name
                                {--id=0 : 采集指定 ID 的电影名称（id 来自豆瓣）}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '采集电影名称';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $id = $this->option('id');

        if ($id <= 0) {
            Movie::query()
                ->where('short_name', null)
                ->where('douban_id', '>', 0)
                ->chunkById(100, function ($movies) {
                    foreach($movies as $movie) {
                        $title = $this->getShortName($movie->douban_id);
                        if (! empty($title)) {
                            $movie->short_name = $title;
                            $movie->save();
                            $this->info('完成电影《' . $title . '》更新！');
                        }
                    }
                });
        } else {
            $title = $this->getShortName($id);
            if (! empty($title) && $movie = Movie::where('douban_id', $id)->first()) {
                $movie->short_name = $title;
                $movie->save();
                $this->info('完成电影《' . $title . '》更新！');
            } else {
                $this->info('未获取到名称或电影不存在！');
            }
        }
    }
    public function getShortName($id)
    {
        $url = config('services.oss.douban.url') . '/' . $id;

        $ql = QueryList::get($url);

        $title = $ql->find('title')->text();
        return trim(str_replace(' (豆瓣)', '', $title));
    }
}
